package com.demo.controller.buyrecord;

import com.demo.common.model.Buyrecord;
import com.demo.common.model.Flighttickets;
import com.demo.service.BuyrecordService;
import com.demo.service.FlightticketsService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

//订票验证
public class BuyrecordValidator extends Validator {

    @Inject
    BuyrecordService buyrecordService;

    @Inject
    FlightticketsService flightticketsService;

    @Override
    protected void validate(Controller controller) {
        validateRequiredString("buyrecord.flightticketsid", "flightticketsidMsg", "请选择机票编号!");

        validateRequiredString("buyrecord.username", "usernameMsg", "请输入登记姓名!");

        validateRequiredString("buyrecord.tel", "telMsg", "请输入电话!");

        validateRequiredString("buyrecord.identitynum", "identitynumMsg", "请输入身份证!");

        validateRequiredString("buyrecord.ticketnum", "ticketnumMsg", "请输入机票数量!");

        String flightticketsid = controller.getPara("buyrecord.flightticketsid");

        if (flightticketsid != null && flightticketsid != "") {
            Flighttickets flighttickets = flightticketsService.findTicketNums(Integer.parseInt(flightticketsid));
            if (flighttickets.getTicketnums() >= flighttickets.getNum() ) {
                addError("errorMsg", "飞机票已经卖完，请订用其它的机票！");
            }
        }

    }

    @Override
    protected void handleError(Controller controller) {
        controller.keepModel(Buyrecord.class);

        String actionKey = getActionKey();
        controller.setAttr("flighttickets", flightticketsService.findAll());
        if (actionKey.equals("/buyrecord/save")) {
            controller.render("add.html");
        } else if (actionKey.equals("/buyrecord/update")) {
            controller.render("edit.html");
        }
    }
}
